// mine/pages/myBlance/myBlance.js
const app = getApp();

Page({
  data: {
    balance: '0.00',
    loading: false,
    error: '',
    recentBills: []
  },

  onLoad() {
    this.refreshAll();
  },

  onShow() {
    this.refreshAll();
  },

  onPullDownRefresh() {
    this.refreshAll(() => wx.stopPullDownRefresh());
  },

  refreshAll(done) {
    this.setData({ loading: true, error: '' });
    Promise.all([this.fetchBalance(), this.fetchRecentBills()])
      .catch(err => {
        console.error('加载失败', err);
        wx.showToast({ icon: 'none', title: '数据加载失败，请稍后重试' });
      })
      .finally(() => {
        this.setData({ loading: false });
        if (typeof done === 'function') done();
      });
  },

  // 获取余额
  fetchBalance() {
    const tryFetch = (urlPath) => {
      return new Promise((resolve, reject) => {
        const token = wx.getStorageSync('token');
        const residentId = app.globalData.residentId || wx.getStorageSync('residentId');
        wx.request({
          url: `${app.globalData.baseUrl}/${urlPath}`,
          method: 'GET',
          data: { residentId },
          header: { 'Authorization': `Bearer ${token}` },
          success: (res) => {
            if (res.data && res.data.code === 200) {
              // 兼容两种返回：{rows: [...]} 或 {data: {...}}
              let balanceValue = 0;
              if (Array.isArray(res.data.rows)) {
                // available_balance 表结构: { id, balance, residentId/resident_id, houseId/house_id, del }
                const rows = res.data.rows;
                const match = rows.find(r => String(r.residentId || r.resident_id) === String(residentId));
                balanceValue = match ? (match.balance || 0) : (rows[0]?.balance || 0);
              } else if (res.data.data) {
                balanceValue = res.data.data.balance || 0;
              } else if (typeof res.data.balance !== 'undefined') {
                balanceValue = res.data.balance || 0;
              }
              this.setData({ balance: parseFloat(balanceValue || 0).toFixed(2) });
              resolve(true);
            } else {
              reject(res.data || { msg: '接口返回异常' });
            }
          },
          fail: (err) => reject(err)
        });
      });
    };

    return new Promise(async (resolve) => {
      const token = wx.getStorageSync('token');
      const residentId = app.globalData.residentId || wx.getStorageSync('residentId');
      if (!token || !residentId) {
        this.setData({ balance: '0.00', error: '' });
        wx.showToast({ icon: 'none', title: '请先登录' });
        try { wx.navigateTo({ url: '/pages/login/login' }); } catch (_) {}
        resolve();
        return;
      }

      // 优先使用 /balance/balance/list，失败再回退到 /availableBalance/availableBalance/list
      try {
        await tryFetch('balance/balance/list');
      } catch (_) {
        try {
          await tryFetch('availableBalance/availableBalance/list');
        } catch (err) {
          console.error('余额获取失败:', err);
          this.setData({ error: '' });
          wx.showToast({ icon: 'none', title: '余额获取失败' });
        }
      }
      resolve();
    });
  },

  // 获取最近账单（最多5条）
  fetchRecentBills() {
    return new Promise((resolve) => {
      const token = wx.getStorageSync('token');
      const residentId = app.globalData.residentId || wx.getStorageSync('residentId');
      if (!token || !residentId) {
        this.setData({ recentBills: [] });
        resolve();
        return;
      }

      wx.request({
        url: `${app.globalData.baseUrl}/bilManagement/bilManagement/list`,
        method: 'GET',
        data: { residentId },
        header: { 'Authorization': `Bearer ${token}` },
        success: (res) => {
          if (res.data && res.data.code === 200 && Array.isArray(res.data.rows)) {
            const list = res.data.rows.map(b => ({
              id: b.id,
              billName: b.billName,
              paymentStatus: b.paymentStatus,
              totalAmount: b.totalAmount,
              chargeStartTime: b.chargeStartTime,
              chargeEndTime: b.chargeEndTime
            }));
            this.setData({ recentBills: list.slice(0, 5) });
          } else {
            this.setData({ recentBills: [] });
          }
        },
        fail: () => this.setData({ recentBills: [] }),
        complete: () => resolve()
      });
    });
  },

  // 前往充值
  goRecharge() {
    wx.navigateTo({ url: '/service/pages/recharge/recharge' });
  },

  // 前往账单列表（沿用生活缴费页）
  goBills() {
    wx.navigateTo({ url: '/service/pages/payment/payment' });
  },

  // 快捷缴费（跳到物业缴费页，按类型筛选可后端支持后拓展）
  quickPay(e) {
    const type = e.currentTarget.dataset.type;
    wx.navigateTo({ url: `/service/pages/property/property?type=${type}` });
  },

  // 点击某条账单
  onBillTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/service/pages/property/property?billId=${id}` });
  }
})